<!--
  智慧社区管理系统 - 工作管理 - 请假记录页面
  @author Wu.Liang
  @date 2025-01-30
  @description 请假记录管理页面，支持分页查询、筛选、审批等功能
-->
<template>
  <div class="leave-record-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-title">
          <el-icon size="24" class="title-icon"><Document /></el-icon>
          <h2>请假记录</h2>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="handleAddLeave">
            <el-icon><Plus /></el-icon>
            新增请假
          </el-button>
          <el-button @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </div>

    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="queryParams" inline>
        <el-form-item label="请假类型">
          <el-select v-model="queryParams.leaveType" placeholder="请选择请假类型" clearable style="width: 150px">
            <el-option label="全部" :value="null" />
            <el-option label="事假" value="personal" />
            <el-option label="病假" value="sick" />
            <el-option label="年假" value="annual" />
            <el-option label="调休" value="compensatory" />
            <el-option label="产假" value="maternity" />
            <el-option label="陪产假" value="paternity" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="请假状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="全部" :value="null" />
            <el-option label="待审批" :value="1" />
            <el-option label="已批准" :value="2" />
            <el-option label="已拒绝" :value="3" />
            <el-option label="已撤销" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请人">
          <el-input v-model="queryParams.applicantName" placeholder="请输入申请人姓名" clearable style="width: 150px" />
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 状态标签 -->
      <div class="status-tabs">
        <el-button
          v-for="tab in statusTabs"
          :key="tab.value"
          :type="currentStatus === tab.value ? 'primary' : ''"
          size="small"
          @click="handleStatusChange(tab.value)"
        >
          {{ tab.label }}
          <el-badge v-if="tab.count > 0" :value="tab.count" class="status-badge" />
        </el-button>
      </div>
    </el-card>

    <!-- 请假记录列表 -->
    <el-card class="table-card" shadow="never" v-loading="loading">
      <el-table :data="leaveList" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="userName" label="申请人" width="120" />
        <el-table-column prop="leaveTypeName" label="请假类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getLeaveTypeType(row.leaveType)">
              {{ row.leaveTypeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120" />
        <el-table-column prop="endDate" label="结束日期" width="120" />
        <el-table-column prop="days" label="请假天数" width="100" />
        <el-table-column prop="reason" label="请假原因" min-width="200" show-overflow-tooltip />
        <el-table-column prop="statusName" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="approverName" label="审批人" width="120" />
        <el-table-column prop="approveTime" label="审批时间" width="160" />
        <el-table-column prop="createTime" label="申请时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button v-if="canApprove(row)" type="success" size="small" @click="handleApprove(row)">
              <el-icon><Check /></el-icon>
              审批
            </el-button>
            <el-button v-if="canCancel(row)" type="warning" size="small" @click="handleCancel(row)">
              <el-icon><Close /></el-icon>
              撤销
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 空状态 -->
    <div v-if="leaveList.length === 0 && !loading" class="empty-state">
      <el-empty description="暂无请假记录" />
    </div>

    <!-- 请假详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="请假详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentLeave" class="leave-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="申请人">{{ currentLeave.userName }}</el-descriptions-item>
          <el-descriptions-item label="请假类型">{{ currentLeave.leaveTypeName }}</el-descriptions-item>
          <el-descriptions-item label="开始日期">{{ currentLeave.startDate }}</el-descriptions-item>
          <el-descriptions-item label="结束日期">{{ currentLeave.endDate }}</el-descriptions-item>
          <el-descriptions-item label="请假天数">{{ currentLeave.days }}天</el-descriptions-item>
          <el-descriptions-item label="请假状态">
            <el-tag :type="getStatusType(currentLeave.status)">{{ currentLeave.statusName }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="请假原因" :span="2">{{ currentLeave.reason }}</el-descriptions-item>
          <el-descriptions-item label="审批人">{{ currentLeave.approverName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="审批时间">{{ currentLeave.approveTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="审批备注" :span="2">{{ currentLeave.approveRemark || '-' }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ currentLeave.createTime }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ currentLeave.updateTime }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 审批弹窗 -->
    <el-dialog
      v-model="approveDialogVisible"
      title="审批请假"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="approveForm" label-width="100px">
        <el-form-item label="申请人">
          <el-input :value="currentLeave?.userName" disabled />
        </el-form-item>
        <el-form-item label="请假类型">
          <el-input :value="currentLeave?.leaveTypeName" disabled />
        </el-form-item>
        <el-form-item label="请假时间">
          <el-input :value="`${currentLeave?.startDate} 至 ${currentLeave?.endDate}`" disabled />
        </el-form-item>
        <el-form-item label="请假原因">
          <el-input :value="currentLeave?.reason" type="textarea" disabled />
        </el-form-item>
        <el-form-item label="审批结果" required>
          <el-radio-group v-model="approveForm.approveResult">
            <el-radio :label="2">批准</el-radio>
            <el-radio :label="3">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批备注">
          <el-input v-model="approveForm.approveRemark" type="textarea" placeholder="请输入审批备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleApproveSubmit" :loading="approving">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Document,
  Plus,
  Refresh,
  View,
  Check,
  Close
} from '@element-plus/icons-vue'
import { workLeaveApi, type LeaveQueryParams, type LeaveVO } from '@/api/work/leave'

// 响应式数据
const loading = ref(false)
const leaveList = ref<LeaveVO[]>([])
const currentStatus = ref<number | null>(null)
const dateRange = ref<[string, string] | null>(null)

// 查询参数
const queryParams = reactive<LeaveQueryParams>({
  current: 1,
  size: 20,
  leaveType: null,
  status: null,
  applicantName: '',
  startDate: null,
  endDate: null
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 状态标签
const statusTabs = ref([
  { label: '全部', value: null, count: 0 },
  { label: '待审批', value: 1, count: 0 },
  { label: '已批准', value: 2, count: 0 },
  { label: '已拒绝', value: 3, count: 0 }
])

// 弹窗控制
const detailDialogVisible = ref(false)
const approveDialogVisible = ref(false)
const currentLeave = ref<LeaveVO | null>(null)
const approving = ref(false)

// 审批表单
const approveForm = reactive({
  approveResult: 2,
  approveRemark: ''
})

// 页面加载
onMounted(() => {
  loadLeaveList()
})

// 加载请假记录列表
const loadLeaveList = async () => {
  try {
    loading.value = true
    
    const params = {
      ...queryParams,
      current: pagination.current,
      size: pagination.size
    }
    
    console.log('查询参数:', params)
    
    const response = await workLeaveApi.getLeavePage(params)
    
    if (response.code === 200 && response.data) {
      leaveList.value = response.data.records || []
      pagination.total = response.data.total || 0
      
      // 更新状态统计
      updateStatusCounts()
      
      console.log('请假记录加载成功:', leaveList.value)
    } else {
      ElMessage.error(response.message || '加载请假记录失败')
    }
  } catch (error) {
    console.error('加载请假记录失败:', error)
    ElMessage.error('加载请假记录失败')
  } finally {
    loading.value = false
  }
}

// 更新状态统计
const updateStatusCounts = () => {
  const counts = { all: 0, pending: 0, approved: 0, rejected: 0 }
  
  leaveList.value.forEach(leave => {
    counts.all++
    if (leave.status === 1) counts.pending++
    else if (leave.status === 2) counts.approved++
    else if (leave.status === 3) counts.rejected++
  })
  
  statusTabs.value[0].count = counts.all
  statusTabs.value[1].count = counts.pending
  statusTabs.value[2].count = counts.approved
  statusTabs.value[3].count = counts.rejected
}

// 获取请假类型样式
const getLeaveTypeType = (type: string) => {
  const typeMap: Record<string, string> = {
    'personal': 'info',
    'sick': 'warning',
    'annual': 'success',
    'compensatory': 'primary',
    'maternity': 'danger',
    'paternity': 'danger',
    'other': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取状态样式
const getStatusType = (status: number) => {
  const statusMap: Record<number, string> = {
    1: 'warning',  // 待审批
    2: 'success',  // 已批准
    3: 'danger',   // 已拒绝
    4: 'info'      // 已撤销
  }
  return statusMap[status] || 'info'
}

// 判断是否可以审批
const canApprove = (leave: LeaveVO) => {
  return leave.status === 1 // 只有待审批状态可以审批
}

// 判断是否可以撤销
const canCancel = (leave: LeaveVO) => {
  return leave.status === 1 // 只有待审批状态可以撤销
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadLeaveList()
}

// 重置
const handleReset = () => {
  Object.assign(queryParams, {
    current: 1,
    size: 20,
    leaveType: null,
    status: null,
    applicantName: '',
    startDate: null,
    endDate: null
  })
  dateRange.value = null
  currentStatus.value = null
  pagination.current = 1
  loadLeaveList()
}

// 状态切换
const handleStatusChange = (status: number | null) => {
  currentStatus.value = status
  queryParams.status = status
  pagination.current = 1
  loadLeaveList()
}

// 日期范围变化
const handleDateRangeChange = (range: [string, string] | null) => {
  if (range) {
    queryParams.startDate = range[0]
    queryParams.endDate = range[1]
  } else {
    queryParams.startDate = null
    queryParams.endDate = null
  }
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadLeaveList()
}

// 当前页变化
const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadLeaveList()
}

// 刷新
const handleRefresh = () => {
  loadLeaveList()
}

// 新增请假
const handleAddLeave = () => {
  ElMessage.info('新增请假功能开发中...')
}

// 查看详情
const handleView = (leave: LeaveVO) => {
  currentLeave.value = leave
  detailDialogVisible.value = true
}

// 审批
const handleApprove = (leave: LeaveVO) => {
  currentLeave.value = leave
  approveForm.approveResult = 2
  approveForm.approveRemark = ''
  approveDialogVisible.value = true
}

// 撤销
const handleCancel = async (leave: LeaveVO) => {
  try {
    await ElMessageBox.confirm('确定要撤销这条请假申请吗？', '确认撤销', {
      type: 'warning'
    })
    
    // 调用撤销API
    const response = await workLeaveApi.cancelLeave(leave.id)
    
    if (response.code === 200) {
      ElMessage.success('撤销成功')
      loadLeaveList()
    } else {
      ElMessage.error(response.message || '撤销失败')
    }
  } catch (error) {
    console.error('撤销请假失败:', error)
  }
}

// 提交审批
const handleApproveSubmit = async () => {
  if (!currentLeave.value) return
  
  try {
    approving.value = true
    
    const response = await workLeaveApi.approveLeave(currentLeave.value.id, {
      approveResult: approveForm.approveResult,
      approveRemark: approveForm.approveRemark
    })
    
    if (response.code === 200) {
      ElMessage.success('审批成功')
      approveDialogVisible.value = false
      loadLeaveList()
    } else {
      ElMessage.error(response.message || '审批失败')
    }
  } catch (error) {
    console.error('审批请假失败:', error)
    ElMessage.error('审批失败')
  } finally {
    approving.value = false
  }
}
</script>

<style scoped>
.leave-record-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-icon {
  color: #409eff;
}

.filter-card {
  margin-bottom: 20px;
}

.status-tabs {
  margin-top: 16px;
  display: flex;
  gap: 8px;
}

.status-badge {
  margin-left: 4px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.leave-detail {
  padding: 20px 0;
}
</style>
